import React, { useEffect, useState } from 'react';
import { Modal, Empty } from 'antd';
import { connect } from 'umi';
import { ReactSortable } from 'react-sortablejs';
import Icon from '@/components/IconPro';
import styles from './index.less';

const NEWS_FUNC = 'news';
const WELCOME_FUNC = 'welcome';

const LayoutModal = ({ homePage, dispatch }) => {
    const [leftEnabled, setLeftEnabled] = useState([]);
    const [rightEnabled, setRightEnabled] = useState([]);
    const [notEnabled, setNotEnabled] = useState([]);

    useEffect(() => {
        const { allModules = [], personalModules = [] } = homePage || {};
        const repairFuncModule = (func, direction) =>
            personalModules
                .map(item => {
                    const { code } = item;
                    if (code === func) {
                        const name = allModules.find(m => m.code === code)?.name || '';
                        return {
                            ...item,
                            position: direction,
                            disabled: true,
                            sort: 1,
                            name
                        };
                    }
                    return null;
                })
                .filter(Boolean);

        const getFuncModule = direction =>
            personalModules
                .map(item => {
                    const { code, position } = item;
                    if (position === direction && code !== WELCOME_FUNC && code !== NEWS_FUNC) {
                        const name = allModules.find(m => m.code === code)?.name || '';
                        return {
                            ...item,
                            name
                        };
                    }
                    return null;
                })
                .filter(Boolean)
                .sort((a, b) => a.sort - b.sort);

        if (allModules.length) {
            const newsFunc = repairFuncModule(NEWS_FUNC, 'left');
            const welcomeFunc = repairFuncModule(WELCOME_FUNC, 'right');
            const leftParts = [...newsFunc, ...getFuncModule('left')];
            const rightParts = [...welcomeFunc, ...getFuncModule('right')];
            const otherParts = allModules
                .map(a => {
                    if (!personalModules.find(p => p.code === a.code)) {
                        return {
                            ...a,
                            disabled: a.disabled || false
                        };
                    }
                    return null;
                })
                .filter(Boolean);
            setLeftEnabled(leftParts);
            setRightEnabled(rightParts);
            setNotEnabled(otherParts);
        }
    }, [homePage]);

    const handleCancel = () => {
        dispatch({
            type: 'homePage/save',
            payload: {
                userLayout: false
            }
        });
    };

    const resolveFuncModule = (funcModules = []) =>
        funcModules.map((item, index) => {
            const { code, position, name } = item;
            return {
                code,
                name,
                position,
                sort: index + 1
            };
        });

    const handleOk = () => {
        const personalModules = [...resolveFuncModule(leftEnabled), ...resolveFuncModule(rightEnabled)];
        dispatch({
            type: 'homePage/savePersonalModules',
            payload: {
                params: personalModules
            },
            callback: () => {
                // 保存后更新首页
                dispatch({
                    type: 'homePage/save',
                    payload: {
                        personalModules,
                        userLayout: false
                    }
                });
            }
        });
    };

    useEffect(() => {
        const handleDrop = e => {
            e.preventDefault();
            e.stopPropagation();
        };
        if (homePage.userLayout) {
            document.body.addEventListener('drop', handleDrop);
        } else {
            document.body.removeEventListener('drop', handleDrop);
        }
    }, [homePage.userLayout]);

    const handleRemoveItem = (item, direction) => {
        if (direction === 'left') {
            const result = leftEnabled.filter(i => i.code !== item.code);
            setLeftEnabled(result);
        } else {
            const result = rightEnabled.filter(i => i.code !== item.code);
            setRightEnabled(result);
        }
        setNotEnabled([...notEnabled, { ...item, position: '' }]);
    };

    const handleAddItem = item => {
        const result = notEnabled.filter(i => i.code !== item.code);
        setLeftEnabled([...leftEnabled, { ...item, position: 'left' }]);
        setNotEnabled(result);
    };

    return (
        <Modal
            width={880}
            title="自定义模块"
            onCancel={handleCancel}
            onOk={handleOk}
            visible={homePage.userLayout}
            okText="提交"
            maskClosable={false}
            destroyOnClose
        >
            <div className={styles.layoutModalWrapper}>
                <p>拖拽可调整顺序：</p>
                <div className={styles.userFuncModule}>
                    <div className={styles.leftFuncModule}>
                        <ReactSortable
                            group="userLayout"
                            list={leftEnabled}
                            setList={state => {
                                const result = state.map(item => ({
                                    ...item,
                                    position: 'left'
                                }));
                                setLeftEnabled(result);
                            }}
                            draggable=".notDisabled"
                            animation={150}
                        >
                            {leftEnabled.map(item => {
                                const { code, name, disabled } = item;
                                return (
                                    <div
                                        key={code}
                                        className={`${styles.sortableItem} ${
                                            !disabled ? 'notDisabled' : styles.disabled
                                        }`}
                                    >
                                        <span>{name}</span>
                                        {item.code === 'often_flow' && (
                                            <Icon.Button
                                                icon="close"
                                                dark
                                                onClick={() => {
                                                    handleRemoveItem(item, 'left');
                                                }}
                                            />
                                        )}
                                    </div>
                                );
                            })}
                        </ReactSortable>
                    </div>
                    <div className={styles.rightFuncModule}>
                        <ReactSortable
                            group="userLayout"
                            list={rightEnabled}
                            draggable=".notDisabled"
                            setList={state => {
                                const result = state.map(item => ({
                                    ...item,
                                    position: 'right'
                                }));
                                setRightEnabled(result);
                            }}
                            animation={150}
                        >
                            {rightEnabled.map(item => {
                                const { code, name, disabled } = item;
                                return (
                                    <div
                                        key={code}
                                        className={`${styles.sortableItem} ${
                                            !disabled ? 'notDisabled' : styles.disabled
                                        }`}
                                    >
                                        <span>{name}</span>
                                        {item.code === 'often_flow' && (
                                            <Icon.Button
                                                icon="close"
                                                dark
                                                onClick={() => {
                                                    handleRemoveItem(item, 'right');
                                                }}
                                            />
                                        )}
                                    </div>
                                );
                            })}
                        </ReactSortable>
                    </div>
                </div>

                <div className={styles.otherFuncModuleWrapper}>
                    <p>请选择需要添加到个人主页的模块：</p>
                    {notEnabled.length <= 0 && (
                        <Empty className={styles.emptyDataSource} image={Empty.PRESENTED_IMAGE_SIMPLE} />
                    )}
                    <div className={styles.otherFuncModule}>
                        {notEnabled.map(item => {
                            const { code, name, disabled } = item;
                            return (
                                <div
                                    key={code}
                                    className={`${styles.sortableItem} ${!disabled ? 'notDisabled' : styles.disabled}`}
                                >
                                    <span>{name}</span>
                                    <Icon.Button icon="plus" dark onClick={() => handleAddItem(item)} />
                                </div>
                            );
                        })}
                    </div>
                </div>
            </div>
        </Modal>
    );
};

export default connect(({ homePage }) => ({ homePage }))(LayoutModal);
